from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from APP01.models import UserInfo
from django.urls import reverse
from django.shortcuts import render

REQUIRE_LOGIN_JSON = [
    '/addcart/',
    '/Changecarts/',
    '/pay/',
]

REQUIRE_LOGIN = [
    '/user_cart/',
    '/order/',
    '/person/',
]


class LoginMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if request.path in REQUIRE_LOGIN_JSON:
            user_id = request.session.get('username')
            if user_id:
                try:
                    user = UserInfo.objects.get(username=user_id)
                    request.user = user
                except:
                    # return render(request,'用户登录与注册/Login2.html')
                    data = {
                        'status': 302,
                        'message': 'user not found'
                    }
                    return JsonResponse(data=data)
            else:
                data = {
                    'status': 302,
                    'mes': 'user not login'

                }
                return JsonResponse(data=data)
        if request.path in REQUIRE_LOGIN:
            user_id = request.session.get('username')
            if user_id:
                try:
                    user = UserInfo.objects.get(username=user_id)
                    request.user = user
                except:
                    return render(request, '用户登录与注册/Login2.html')

            else:

                return render(request, '用户登录与注册/Login2.html')
